﻿using Evision.Insure;
using Evision.Zlsoft.Miaiap.Core.Model;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Zlsy.Core.Data;

namespace Evision.Zlsoft.Miaiap.Core.Service {
    public static class ModelApproval {
        //private Ado _ado;
        private static Zlsy.Core.ILogger _logg = Zlsy.Core.Log.GetLog("MIAIAP");
        //public ModelApproval() {
        //    _ado = Ado.Default;
        //}
        /// <summary>
        /// 处方审批
        /// </summary>
        /// <param name="patiendId">病人id</param>
        /// <param name="pageId">主页id</param>
        /// <param name="sendNo">发送号</param>
        /// <param name="strNo">挂号no</param>
        /// <param name="outorin">住院或者门诊</param>
        /// <returns></returns>
        public static InputPrescriptionApproval GetMiaiapApproval(Int32 patiendId, Int32 varRecId, string[] arrData, bool outorin) {
            List<MedicalRecord> medicalRecords = new List<MedicalRecord>();
            foreach (string item in arrData) {
                MedicalRecord medical = ParseDataToRecord(item);
                medicalRecords.Add(medical);
                _logg.Info($"ID: {medical.ID},开嘱医生: {medical.开嘱医生},开嘱科室ID: {medical.开嘱科室ID},医嘱期效: {medical.医嘱期效},收费细目ID: {medical.收费细目ID},诊疗项目ID: {medical.诊疗项目ID},varRecId:{varRecId}");
            }
            _logg.Error($"处方审批arrData：{arrData[0]}");

            _logg.Info($"数量: {medicalRecords.Count}");
            // 输出列表的内容
            //foreach (var record in medicalRecords) {
            //    _logg.Info($"ID: {record.ID}, Name: {record.Name}, Content: {record.Content},ChargeDetailID: {record.ChargeDetailID}");
            //}
            try {
                InputPrescriptionApproval inputPrescription = new InputPrescriptionApproval();
                inputPrescription.prescriptions = new List<Prescription>();
                //病人基本信息
                List<Object> list = new List<object>();

                string sqlpublicout = "";
                if (outorin) {
                    //sqlpublicout.Append(" and a.病人id =? and b.no = ?  and b.记录性质 =1");
                    //list.Add(patiendId);
                    //list.Add(varRecId);
                    sqlpublicout = @"SELECT * FROM (
                                                    SELECT  
                                                        p.门诊号,
                                                        p.住院号, 
                                                        b.执行部门id AS 病区号,
                                                        p.姓名,
                                                        p.出生日期,
                                                        p.性别,
                                                        a.就诊时间,
                                                        p.身份证号,
                                                        a.YB流水号,
                                                        a.医疗类别
                                                    FROM 
                                                        就诊登记记录 a
                                                    LEFT JOIN 
                                                        病人挂号记录 b ON a.病人id = b.病人id
                                                    JOIN 
                                                        病人信息 p ON p.病人id = a.病人id
                                                    WHERE 
                                                        a.病人id = ? 
                                                        AND b.id = ? 
                                                        AND b.记录性质 = 1 
                                                    ORDER BY 
                                                        a.就诊时间 DESC
                                                ) 
                                                WHERE ROWNUM = 1";
                } else {
                    //sqlpublicout.Append(" and a.病人id =? and q.主页id = ?");
                    //list.Add(patiendId);
                    //list.Add(varRecId);
                    sqlpublicout = @"SELECT *
                                FROM (
                                    SELECT  
                                        p.门诊号,
                                        p.住院号, 
                                        q.出院病床 AS 床位号,
                                        b.执行部门id AS 病区号,
                                        p.姓名,
                                        p.出生日期,
                                        p.性别,
                                        a.就诊时间,
                                        p.身份证号,
                                        a.YB流水号,
                                        a.医疗类别
                                    FROM 
                                        就诊登记记录 a
                                    JOIN 
                                        病人信息 p ON p.病人id = a.病人id
                                    LEFT JOIN 
                                        病人挂号记录 b ON a.病人id = b.病人id
                                    LEFT JOIN 
                                        病案主页 q ON q.病人id = a.病人id
                                    WHERE 
                                        and a.病人id = ? and q.主页id = ?
                                    ORDER BY 
                                        a.就诊时间 DESC
                                ) WHERE ROWNUM = 1";
                }
                _logg.Info($"查询患者基本信息：{sqlpublicout}");
                DataRow drpublic = Adodb.QueryForRow(sqlpublicout, patiendId, varRecId);
                List<DiagnoseData> diagnoseDatas = new List<DiagnoseData>();
                if (drpublic != null) {
                    //inputPrescription.isITEM = 1;
                    //inputPrescription.isUplode = 0; 
                    //inputPrescription.uploadTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                    //inputPrescription.hospitalizationFlag = outorin ? "op" : "ip";
                    //inputPrescription.treatmentType = 5;
                    //inputPrescription.treatmentCode = outorin ? drpublic["就诊号"].ToString(): drpublic["住院号"].ToString();
                    //inputPrescription.bedNumber = drpublic["床位号"].ToString();
                    //inputPrescription.areaCode = drpublic["病区号"].ToString();
                    //string[] parts = medicalRecords[0].诊断信息.Split(new string[] { "<SPCOLS>" }, StringSplitOptions.None);
                    //Evision.Zlsoft.Miaiap.Core.Model.Patient patient = new Evision.Zlsoft.Miaiap.Core.Model.Patient();
                    //patient.name = drpublic["姓名"].ToString();
                    //DateTime birthDate = Convert.ToDateTime(drpublic["出生日期"]);
                    //patient.birth = birthDate.ToString("yyyy-MM-dd");
                    //patient.sex = drpublic["性别"].ToString();
                    //DiagnoseData diagnoseData = new DiagnoseData();
                    //diagnoseData.name = parts[1];
                    //diagnoseData.code = parts[2];
                    //diagnoseDatas.Add(diagnoseData);
                    //patient.diagnoseDatas = diagnoseDatas;
                    //inputPrescription.patientInfo = patient;
                    inputPrescription.isITEM = "1";
                    inputPrescription.isUplode = "0";
                    inputPrescription.uploadTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                    inputPrescription.hospitalizationFlag = outorin ? "op" : "ip";
                    inputPrescription.treatmentType = outorin ? "op" : "ip";
                    inputPrescription.treatmentCode = drpublic["YB流水号"]?.ToString() ?? string.Empty;
                    inputPrescription.lisAdmNo = drpublic["YB流水号"]?.ToString() ?? string.Empty;
                    inputPrescription.bedNumber =string.Empty;
                    inputPrescription.areaCode = string.Empty;

                    HisPatient patient = new HisPatient();
                    patient.name = drpublic["姓名"]?.ToString() ?? string.Empty;

                    if (DateTime.TryParse(drpublic["出生日期"]?.ToString(), out DateTime birthDate)) {
                        patient.birth = birthDate.ToString("yyyy-MM-dd");
                    } else {
                        patient.birth = string.Empty; // 设定为默认空值
                    }

                    patient.sex = drpublic["性别"]?.ToString() ?? string.Empty;
                    patient.medicalRecord  = drpublic["身份证号"]?.ToString() ?? string.Empty;
                    patient.cardType = "18";
                    patient.cardCode = drpublic["YB流水号"]?.ToString() ?? string.Empty;
                    patient.pregnantUnit = "周";


                    // 按 <SPROWS> 分割行
                    string[] rows = medicalRecords[0].诊断信息.Split(new[] { "<SPROWS>" }, StringSplitOptions.None);
                    foreach (string row in rows) {
                        // 按 <SPCOLS> 分割列
                        string[] columns = row.Split(new[] { "<SPCOLS>" }, StringSplitOptions.None);
                        DiagnoseData diagnoseData = new DiagnoseData();
                        diagnoseData.name = columns[1];
                        diagnoseData.code = columns[3];
                        diagnoseDatas.Add(diagnoseData);
                    }

                    //DiagnoseData diagnoseData = new DiagnoseData();
                    //diagnoseData.name = parts.Length > 1 ? parts[1] : string.Empty; // 设定为默认空值
                    //diagnoseData.code = parts.Length > 2 ? parts[3] : string.Empty; // 设定为默认空值

                    //if (diagnoseDatas == null) {
                    //    diagnoseDatas = new List<DiagnoseData>(); // 确保列表被初始化
                    //}
                    //diagnoseDatas.Add(diagnoseData);

                    patient.diagnoseDatas = diagnoseDatas;
                    inputPrescription.patientInfo = patient;

                    SIData siData = new SIData();
                    siData.medicalType = drpublic["医疗类别"]?.ToString() ?? string.Empty;
                    patient.SiData = siData;
                    // 遍历字符串数组，将每个元素转换成整数并添加到List中  
                    foreach (MedicalRecord medicalAdvice in medicalRecords) {

                        //门诊医嘱id 处方号
                        Prescription prescription = new Prescription();
                        prescription.prescriptionId = medicalAdvice.ID.ToString();
                        prescription.reason = "无";
                        prescription.isCirculation = "1";
                        prescription.isUrgent = "0";
                        prescription.isNew = "1";
                        prescription.isCurrent = "1";
                        prescription.doctorCode = Adodb.GetScalar<string>("select ID from  人员表 where 姓名 = ? and rownum < 2", medicalAdvice.开嘱医生);
                        prescription.doctorName = medicalAdvice.开嘱医生;
                        prescription.departmentCode = medicalAdvice.开嘱科室ID;
                        //Adodb.GetScalar<string>("select 编码 from  部门表 where ID = ? and rownum < 2", medicalAdvice.开嘱科室ID);
                        prescription.departmentName = Adodb.GetScalar<string>("select 名称 from  部门表 where ID = ? and rownum < 2", medicalAdvice.开嘱科室ID);
                        prescription.presType = medicalAdvice.医嘱期效 == "1" ? "L" : "T";
                        prescription.presTime = medicalAdvice.开嘱时间.ToString("yyyy-MM-dd HH:mm:ss");
                        //根据医嘱id查询药品
                        string sqlmedout = "";
                        prescription.medicines = new List<Evision.Zlsoft.Miaiap.Core.Model.Medicine>();
                        DataTable dtmedout = new DataTable();
                        //MessageBox.Show("收费细目ID", medicalAdvice.收费细目ID.ToString());
                        if (medicalAdvice.收费细目ID > 0) {
                            sqlmedout = @"select CASE WHEN a.类别 IN ('5', '6', '7') THEN 1 ELSE 0 END AS 是否药品,a.名称 AS 项目名称,
                                                         a.编码 AS 项目编码,
                                                        CASE 
                                                            WHEN b.编码 = '5' THEN 1
                                                            WHEN b.编码 = '6' THEN 2
                                                            WHEN b.编码 = '7' THEN 3 
                                                            WHEN b.编码 = 'F' THEN 5
                                                            WHEN b.编码 = 'C' THEN 6
                                                            WHEN b.编码 = 'D' THEN 7 
                                                            ELSE 8  
                                                            END AS 编码分类,
                                                             a.规格
                                                            FROM 收费项目目录 a,收费项目类别 b  where a.类别 = b.编码 AND a.id = ?";
                            dtmedout = Adodb.QueryForTable(sqlmedout, medicalAdvice.收费细目ID);
                        } else {
                            //MessageBox.Show("诊疗ID", medicalAdvice.诊疗项目ID.ToString());
                            sqlmedout = @"    select CASE WHEN a.类别 IN ('5', '6', '7') THEN 1 ELSE 0 END AS 是否药品,a.名称 AS 项目名称,
                                                         a.编码 AS 项目编码,
                                                        CASE 
                                                            WHEN b.编码 = '5' THEN 1
                                                            WHEN b.编码 = '6' THEN 2
                                                            WHEN b.编码 = '7' THEN 3 
                                                            WHEN b.编码 = 'F' THEN 5
                                                            WHEN b.编码 = 'C' THEN 6
                                                            WHEN b.编码 = 'D' THEN 7 
                                                            ELSE 8  
                                                            END AS 编码分类
                                                            FROM 诊疗项目目录 a,诊疗项目类别 b  where a.类别 = b.编码 AND a.id = ?";
                            dtmedout = Adodb.QueryForTable(sqlmedout, Convert.ToInt32(medicalAdvice.诊疗项目ID));
                        }
                        _logg.Info($"查询药品信息：{sqlmedout}");
                        foreach (DataRow rowmedout in dtmedout.Rows) {
                            Evision.Zlsoft.Miaiap.Core.Model.Medicine medicine = new Evision.Zlsoft.Miaiap.Core.Model.Medicine();
                            medicine.pydCode = rowmedout["是否药品"].ToString();
                            medicine.name = rowmedout["项目名称"].ToString();
                            medicine.code = rowmedout["项目编码"].ToString();
                            medicine.insurCode = rowmedout["项目编码"].ToString();
                            medicine.itemType = rowmedout["编码分类"].ToString();
                            medicine.insurType = "1";
                            medicine.group = "1";
                            medicine.linkGroup = "1";
                            medicine.reason = medicalAdvice.用药理由.ToString();
                            medicine.dose = medicalAdvice.单次用量.ToString();
                            medicine.freq  = medicalAdvice.频率次数.ToString();
                            medicine.administer = medicalAdvice.执行频次.ToString();
                            medicine.days = medicalAdvice.天数.ToString(); 
                            //medicine.spec = rowmedout["规格"].ToString();
                            medicine.preventiveFlag = "1";
                            prescription.medicines.Add(medicine);
                        }
                        inputPrescription.prescriptions.Add(prescription);
                }
            }
    

                

                ////住院部分
                //foreach (DataRow row in dt.Rows) {
                //        //住院医嘱
                //        string sqlpresin = @"SELECT a.no 处方号,
                //                            a.是否急诊 是否紧急处方,
                //                            f.编号 开嘱医生代码,
                //                            g.开嘱医生 开嘱医生姓名,
                //                            g.开嘱科室id 开嘱科室代码,
                //                            d.名称 开嘱科室姓名,
                //                            g.id 医嘱id
                //                            FROM 住院费用记录 a
                //                            JOIN 
                //                            病人医嘱记录 g ON a.医嘱序号 = g.ID
                //                            JOIN 
                //                            人员表 f ON g.开嘱医生 = f.姓名
                //                            JOIN 
                //                            部门表 d ON g.开嘱科室id = d.id
                //                            JOIN 病人挂号记录 b ON  a.挂号ID=b.ID
                //                            WHERE a.病人id =? and a.主页id =? and a.病人来源=2 and g.id = ？";

                //        DataTable dtpresin = _ado.QueryForTable(sqlpresin, patiendId,pageId,row["医嘱id"]);
                //        foreach (DataRow rowpresin in dtpresin.Rows) {
                //            Prescription prescription = new Prescription();
                //            prescription.prescriptionId = rowpresin["处方号"].ToString();
                //            prescription.reason = "";
                //            prescription.isUrgent = Convert.ToInt32(rowpresin["是否紧急处方"]);
                //            prescription.doctorCode = rowpresin["开嘱医生姓名"].ToString();
                //            prescription.doctorName = rowpresin["开嘱医生姓名"].ToString();
                //            prescription.departmentCode = rowpresin["开嘱科室代码"].ToString();
                //            prescription.departmentName = rowpresin["开嘱科室姓名"].ToString();
                //            //住院药品
                //            string sqlmedin = @"SELECT
                //                             CASE WHEN g.诊疗类别 IN('5','6','7') THEN 1 ELSE 0 END AS 是否药品,
                //                                c.名称 项目名称,
                //                                c.编码 项目编码,
                //                                c.规格,
                //                                NVL(a.付数, 0) * a.数次 AS 项目数量,
                //                                a.计算单位 项目数量单位,
                //                                a.标准单价 AS 项目单价 
                //                                FROM 
                //                                住院费用记录 a  
                //                                JOIN 
                //                                病人医嘱记录 g ON a.医嘱序号 = g.ID
                //                                JOIN 
                //                                收费项目目录 c ON a.收费细目id = c.id
                //                                JOIN  病人挂号记录 b ON  a.挂号ID=b.ID
                //                                WHERE a.病人id =? and a.主页id =? and g.id = ? and b.记录性质 = 1";
                //        DataTable dtmedin = _ado.QueryForTable(sqlmedin,patiendId,pageId, rowpresin["医嘱id"]);
                //        foreach (DataRow rowmedout in dtmedin.Rows) {
                //            Medicine medicine = new Medicine();
                //            medicine.isMedicine = Convert.ToInt32(rowmedout["是否药品"]);
                //            medicine.name = rowmedout["项目名称"].ToString();
                //            medicine.code = rowmedout["项目编码"].ToString();
                //            medicine.specification = rowmedout["规格"].ToString();
                //            medicine.quantity = Convert.ToInt32(rowmedout["项目数量"]);
                //            medicine.quantityUnit = rowmedout["项目数量单位"].ToString();
                //            medicine.price = Convert.ToInt32(rowmedout["项目单价"]);
                //            prescription.medicines.Add(medicine); 
                //        }
                //        inputPrescription.prescriptions.Add(prescription);
                //    }
                //}

                return inputPrescription;
            } catch (Exception ex) {
                return new InputPrescriptionApproval();
                _logg.Error($"处方审批报错：{ex}");
            }
        }
        public static MedicalRecord ParseDataToRecord(string data) {
            MedicalRecord record = new MedicalRecord();
            string[] pairs = data.Split(',');

            foreach (var pair in pairs) {
                string[] keyValue = pair.Split('=');
                if (keyValue.Length != 2) continue;

                string key = keyValue[0].Trim();
                string value = keyValue[1].Trim();

                switch (key) {
                    case "ID": record.ID = value; break;
                    case "相关ID": record.相关ID = value; break;
                    case "前提ID": record.前提ID = value; break;
                    case "病人来源": record.病人来源 = value; break;
                    case "病人ID": record.病人ID = value; break;
                    case "主页ID": record.主页ID = value; break;
                    case "挂号单": record.挂号单 = value; break;
                    case "婴儿": record.婴儿 = value; break;
                    case "姓名": record.姓名 = value; break;
                    case "性别": record.性别 = value; break;
                    case "年龄": record.年龄 = value; break;
                    case "病人科室ID": record.病人科室ID = value; break;
                    case "序号": record.序号 = value; break;
                    case "医嘱状态": record.医嘱状态 = value; break;
                    case "医嘱期效": record.医嘱期效 = value; break;
                    case "诊疗类别": record.诊疗类别 = value; break;
                    case "诊疗项目ID": record.诊疗项目ID = int.Parse(value); break;
                    case "标本部位": record.标本部位 = value; break;
                    case "检查方法": record.检查方法 = value; break;
                    case "收费细目ID": record.收费细目ID = int.Parse(value); break;
                    case "天数": record.天数 = value; break;
                    case "单次用量": record.单次用量 = value; break;
                    case "总给予量": record.总给予量 = value; break;
                    case "医嘱内容": record.医嘱内容 = value; break;
                    case "医生嘱托": record.医生嘱托 = value; break;
                    case "执行科室ID": record.执行科室ID = value; break;
                    case "执行频次": record.执行频次 = value; break;
                    case "频率次数": record.频率次数 = value; break;
                    case "频率间隔": record.频率间隔 = value; break;
                    case "间隔单位": record.间隔单位 = value; break;
                    case "执行时间方案": record.执行时间方案 = value; break;
                    case "计价特性": record.计价特性 = value; break;
                    case "执行性质": record.执行性质 = value; break;
                    case "执行标记": record.执行标记 = value; break;
                    case "可否分零": record.可否分零 = value; break;
                    case "紧急标志": record.紧急标志 = value; break;
                    case "开始执行时间": record.开始执行时间 = DateTime.Parse(value); break;
                    case "执行终止时间":
                        if (!string.IsNullOrEmpty(value))
                            record.执行终止时间 = DateTime.Parse(value);
                        break;
                    case "开嘱科室ID": record.开嘱科室ID = value; break;
                    case "开嘱医生": record.开嘱医生 = value; break;
                    case "开嘱时间": record.开嘱时间 = DateTime.Parse(value); break;
                    case "摘要": record.摘要 = value; break;
                    case "用药目的": record.用药目的 = value; break;
                    case "用药理由": record.用药理由 = value; break;
                    case "申请序号": record.申请序号 = value; break;
                    case "手术情况": record.手术情况 = value; break;
                    case "疾病ID": record.疾病ID = value; break;
                    case "编辑状态": record.编辑状态 = value; break;
                    case "附项": record.附项 = value; break;
                    case "申请": record.申请 = value; break;
                    case "诊断信息": record.诊断信息 = value; break;
                }
            }

            return record;
        }

    }
}

